<?php

class LawAction extends Action {
  private $_dev = 0;
  function _initialize() {
    $this->_dev = C("DEV_FLAG");
    $this->assign("istp", 1);//circle-header2中有TP和PHPWIND都用到，加上这个参数进行区别
  }
  //截取utf8字符串
  public function utf8Substr($str, $from, $len) {
    return preg_replace('#^(?:[\x00-\x7F]|[\xC0-\xFF][\x80-\xBF]+){0,'.$from.'}'.
      '((?:[\x00-\x7F]|[\xC0-\xFF][\x80-\xBF]+){0,'.$len.'}).*#s',
      '$1',$str);
  }

  public function index() {
    $m = M('ALawtype');
    $lawType = $m->order("px")->findAll();
    $rt = array();
    $rt = $this->_getHZRList(array('a_zy','a_hy','a_region'));
    $newList = $m->query("select id,ltitle as title,ldate_pub as datetime from a_law order by ldate_pub desc limit 0,20");
    foreach ($newList as $i => $l) {
      $title = $l['title'];
      if (strtotime($l['datetime'])-strtotime("-15 days") >= 0) {
        $newList[$i]["isnews"] = 1;
        $title = $this->utf8Substr($title, 0,11);
        $newList[$i]['stitle'] = $title;
      }else {
        $newList[$i]["isnews"] = 0;
        $title = $this->utf8Substr($title, 0,13);
        $newList[$i]['stitle'] = $title;
      }
    }
	
	$db=M('ALaw');
	$typeArr=$db->field('lawtype_id as id,a_lawtype.Laytype_name as title')->where('lawtype_id>0')->group('lawtype_id')->order('px ASC')->join('a_lawtype on a_lawtype.id=a_law.lawtype_id')->select();
	
	$this->assign("typeArr", $typeArr);
	//print_r($typeArr);//exit();
    $this->assign("newList", $newList);
    $this->assign("classify", $rt);
    $this->assign('lawType', $lawType);
    $this->assign('dev', $this->_dev);
    $this->display();
  }



  /*  params: type        1-专业，2-行业，3-地区,4-分类
   *  params: level       1-一级分类，2-2级分类
   *  params: id          type对应的id（1-zi_id,2-hy_id,3-dq_id）
   *  params: lawType_id  a_lawtype对应的id，如果存在则直接选择对应的记录即可，不用理会以上的参数了
   * **/

  public function search() {
    $classify = array(id=>array(1=>"zy_id",2=>"hy_id",3=>"dq_id"),
	                  table=>array(1=>"a_zy",2=>"a_hy",3=>"a_region"),
					  title=>array(1=>'【@专业相关法律】--EHS中国',2=>'【ehs@行业相关法律】--EHS中国',3=>'【ehs@地区相关法律】--EHS中国')
					  );
    $classifyID = $classify["id"][$_GET["type"]];
    $table = $classify["table"][$_GET["type"]];
	
    $m = M();
    if (!empty($_GET['lawType_id'])) {
      $m2=M('ALawtype');
	  $title=$m2->where('id='.$_GET['lawType_id'])->getField('Laytype_name');
	  $title='【ehs'.$title.'相关法律】-EHS中国-';
	 // $title = str_replace('@',$title,$classify["title"][$_GET["type"]]);	
      $count = $m->query("select count(*) from a_law where lawtype_id = ".$_GET["lawType_id"]);
      $sql = "select id,ltitle as title,ldate_pub as date_pub,luser as issue from a_law where lawtype_id =".$_GET["lawType_id"];
    }else {
	  $title='';
	  if(!empty($_GET['id']) && !empty($_GET['type'])){
		  $oid=$_GET['id'];
		  $ltype=$_GET['type'];
		  if($ltype==1)
		    $m2=M('AZy');
		  else 
		    $m2=M('AZy');
		  $title=$m2->where("id=".$oid)->getField('title');
	  }
      $title=str_replace('@',$title,$table = $classify["title"][$_GET["type"]]);
      $select = "select t1.id,t1.ltitle as title,t1.luser as issue,t1.ldate_pub as date_pub,t1.zy_id,t2.title as zy_title,t1.hy_id,t3.title as hy_title,t1.dq_id,t4.title as dq_title,t1.lawtype_id as lawtype_id,t5.Laytype_name as lawtype_title ";
      $selectCount = "select count(*) ";
      $from = " from a_law t1
        left join a_zy t2 on (t1.zy_id = t2.id)
        left join a_hy t3 on (t1.hy_id = t3.id)
        left join a_region t4 on (t1.dq_id = t4.id)
        left join a_lawtype t5 on (t1.lawtype_id=t5.id) ";
      /*if ($_GET["level"] == 1) {
        $sql = "select id from $table where did=".$_GET["id"];
        $idl = $m->query($sql);
        foreach($idl as $k => $v) {
          $ids[] = $v["id"];
        }*/
		
		if (($_GET["level"]== 1 && $_GET["level"] <3)||($_GET["level"]== 2 && $_GET["level"] ==1)) {
        	$kids=$this->_getFinalKids($table,$_GET['id']);
			$ids=array();
        	foreach($kids as $kid)
			  $ids[]=$kid['id'];
			if(!count($ids)) 
				$ids=0;
			else
			    $ids=implode(',',$ids);
        	if ($_GET['type'] == 3) 
				$ids .= ",".$_GET['id'];
        	$where = "where t1.$classifyID in ($ids)";
      	}else {
           $where = "where t1.$classifyID=".$_GET["id"];
      	}
      	$count = $m->query($selectCount.$from.$where);
      	$sql = $select.$from.$where;
    }
	//echo $m->getLastSQL();
    $order = " order by date_pub desc";
    $count = $count[0]["count(*)"];
    import("@.ORG.Page"); //导入分页类
    $records = 20;//每页多少条记录
    $p = new Page ($count,$records);
    $p->setConfig('header','篇记录');
    $p->setConfig('prev',"上一页");
    $p->setConfig('next','下一页');
    $p->setConfig('first','<<');
    $p->setConfig('last','>>');
    $page = $p->show ();
    $limit = " limit ".$p->firstRow.",".$p->listRows;
    $list = $m->query($sql.$order.$limit);
    $this->assign("count", $count);
	$this->assign("title", $title);
    $this->assign("resultList", $list);
    $this->assign("nowPage",$p->nowPage);
    $this->assign("page", $page );
    $this->assign("records",$records);
    /*-------------  左边列表数据  ----------------*/
    $lawType = $m->query("select * from a_lawtype");
    $rt = $this->_getHZRList(array('a_zy','a_hy','a_region'));
    $this->assign("lawType", json_encode($lawType));
    $this->assign("hzrList", json_encode($rt));
    $treeCookie = $_COOKIE['cstree']>0?1:0;
    $this->assign("treeCookie", $treeCookie);
    $dq = "<script></script>";
    $this->display();
  }

  private function _getHZRList($table) {
    $m = M();
    $rt = array();
    foreach ($table as $k => $v) {
      $list = $m->query("select * from $v");
      $rt[$k] = $this->_reList(array(),$list,0);
    }
    return $rt;
  }

  private function _reList($rt,$list,$did) {
    foreach ($list as $k => $v) {
      if ($did == $v["did"]) {
        $rt[$k] = array(id=>$v["id"],title=>$v["title"],law_count=>$v['law_count'],downLine=>array());
        $rt[$k]["downLine"] = $this->_reList(array(),$list,$v['id']);
      }
    }
    return $rt;
  }

  //高级搜索
  public function advancedSearch() {

    $this->display("advanced-search");
  }

  public function ajaxAdavancedSearch() {
    $selects = $_POST['select'];
    $words = $_POST['word'];
    //如果多个地方使用，可以考虑弄成私有变量，以后优化这个变量的构造
    $advance_search = array(
      word => array(1=>$words[1],2=>$words[2],3=>$words[3],4=>$words[4]),//这句可以用word=>$words代替，只不是目前为了方便理解所以这样写
      select => array(//与或非
        1=>$words[1]!=""?" @ltitle ".$words[1]:"",
        2=>array(
          2=>$words[2]!=""?" @lcontent ".$words[2]:"",
          3=>"",
          4=>"",
        ),
        3=>array(
          2=>$words[3]!=""?" @luser ".$words[3]:"",
          3=>"",
          4=>""
        ),
        4=>array(
          2=>$words[4]!=""?" @lnumber ".$words[4]:"",
          3=>"",
          4=>""
        ),
      ),
    );
    //$sql = "select * from a_law where 1".$advance_search["select"][1];
    $search = $advance_search["select"][1];
    for ($i = 2; $i < 5; $i ++) {
      $search .= $advance_search["select"][$i][$selects[$i]];
    }
    $m = M();
    import("@.ORG.Sphinxapi"); //导入Sphinxapi
    $cl = new SphinxClient ();
    $cl->SetServer('127.0.0.1', 9312);
    $cl->SetConnectTimeout(3);
    $cl->SetArrayResult(true);
    $cl->SetMatchMode(SPH_MATCH_EXTENDED);
    $index = "law_index";
    $count = $this->_getAdvancedSearchCount($cl,$search,$index);
    $record = 20;
    if ($count > 0) {
      $page = $_POST['page']>0?$_POST['page']:1;
      $list = $this->_getAdvancedSearchList($cl,$search,$index,$page,$record);
    } else $page = 0;
    $rt["count"] = $count;
    $rt["record"] = $record;
    $rt["page"] = $page;
    $rt["list"] = $list;
    $this->ajaxReturn($rt);
  }

  private function _getAdvancedSearchCount($cl,$search,$index) {
    $result = $cl->Query($search, $index);
    $count = $result['total'];
    return $count;
  }

  private function _getAdvancedSearchList($cl,$search,$index,$page,$record) {
    $cl->SetLimits(($page-1)*$record,$record);
    $cl->SetSortMode(SPH_SORT_EXTENDED,"@id desc");
    $result = $cl->Query($search,$index);
    $matches = $result['matches'];
    $ids = array();
    foreach ($matches as $k => $v) {
      $ids[] = $v['id'];
    }
    $m = M();
    $sql = "select id,ltitle,luser,ldate_pub from a_law where id in (".implode(',', $ids).")";
    $list = $m->query($sql);
    return $list;
  }
  
  /*返回第三级子分类*/
  private function _getFinalKids($table,$pid){
    $m=M($table);
	if(!is_array($pid))
		$list=$m->field('id')->where("did=".$pid)->select();
	else {
	    $ids=implode(',',$pid);
		$list=$m->field('id')->where("did in($ids)")->select();
	  }
	 
	if($list) {
		$ids=array();
	   foreach($list as $li) {
	     $ids[]=$li['id'];
	   }
	     $list=$this->_getFinalKids($table,$ids);
	   }
	 else{
	   if(!is_array($pid))
		$list=$m->where("id=".$pid)->select();
	  else {
	    $ids=implode(',',$pid);
		$list=$m->where("id in($ids)")->select();
	   }
	  }
	return $list; 
  }
  
}
?>
